import datetime
from multiprocessing import Process
from threading import Thread

from .connect_mysql import Mysql
from random import shuffle
import pymysql


class DesenData:

    def main(databases_info):
        query_database_info = {'address': databases_info["s_address"], 'types': databases_info["s_types"],
                               'passwd': databases_info["s_passwd"], 'port': databases_info["s_port"],
                               'user': databases_info["s_user"], "sql": databases_info["data"]}
        insert_database_info = {'address': databases_info["d_address"], 'types': databases_info["d_types"],
                                'passwd': databases_info["d_passwd"], 'port': databases_info["d_port"],
                                'user': databases_info["d_user"]}
        limit = databases_info["limit"]
        fieldinfo_list = query_database_info["sql"]
        # list11 = [i for i in fieldinfo_list]
        results_data = []
        feild_list = []
        for querys in range(len(fieldinfo_list)):
            fieldinfos = fieldinfo_list[querys][0]
            # print(fieldinfo_list[querys][0])
            db_name = fieldinfos["dbname"]
            table_name = fieldinfos["tablename"]
            feild = fieldinfos["fieldname"]
            feild_list.append(feild)
        feilds = ','.join(feild_list)
        count_sql = "select COUNT(*) from " + db_name + "." + table_name
        count_info = query_database_info
        count_info.update({"sql": count_sql, "database": db_name})
        max_counts = Mysql.SelectDatabase(count_info)
        max_limit = max_counts[0]["COUNT(*)"]
        if int(max_limit)//int(1000) <= 1:
            query_num = 1
        elif int(max_limit)//int(1000) > 1:
            query_num = int(max_limit)//5
        q_i = 0
        for q_i in range(query_num+1):
            sql = "select " + feilds + " from " + db_name + "." + table_name + " limit " + str(q_i*5) + " , " + str(5)
            query_database_info.update({"sql": sql, "database": db_name})
            feild_data = Mysql.SelectDatabase(query_database_info)
            desen_data = DesenData.shuffle_str(feild_data)
            insert_database_info.update({"database": db_name, "table": table_name, "sql": sql})
            res = DesenData.InsertData(desen_data, insert_database_info)
            results_data.append(res)
        results_res = {"code": "200", "max_number": max_limit, "res": results_data}
        return results_res

    def shuffle_str(feild_data):
        for data in feild_data:
            for keys, values in data.items():
                value = data[keys]
                if keys != "id" and len(str(value)) > 4 \
                        and type(value) is not datetime.datetime:
                    value_list = list(value)
                    shuffle(value_list)
                    desen_vaule = ''.join(value_list)
                    data[keys] = desen_vaule
        return feild_data

    def InsertData(desen_data, insert_database_info):
        host = insert_database_info['address']
        user = insert_database_info["user"]
        passwd = insert_database_info["passwd"]
        port = insert_database_info["port"]
        database = insert_database_info["database"]
        db_table = insert_database_info["database"]+"."+insert_database_info["table"]
        insert_sql_list = []
        for insert_data in desen_data:
            row_data = ''
            col_data = ''
            for key in insert_data.keys():
                # if key != "id":
                row_data = (row_data + "'%s'" + ",") % (insert_data[key])
                col_data = (col_data + "%s" + ',') % key
            insert_sql = "insert into %s (%s) values (%s)" % (db_table, col_data[:-1], row_data[:-1])
            insert_sql_list.append(insert_sql)
        db_conn = pymysql.connect(host=host, port=int(port),
                                  user=user, passwd=passwd,
                                  db=database, charset='utf8')
        cursor = db_conn.cursor()

        if insert_sql_list:
            for sql in insert_sql_list:
                try:
                    cursor.execute(sql)
                    db_conn.commit()
                except:
                    db_conn.rollback()
            cursor.close()
            db_conn.close()
            status = {"执行状态": "数据插入成功!", "查询sql": insert_database_info["sql"]}
        else:
            status = {"执行状态": "数据插入失败!", "查询sql": insert_database_info["sql"]}

        return status


class MyThread(Thread):
    def run(self) -> None:
        self.task()

    def task(self):
        res = DesenData.main(self._kwargs)
        return res


class MyProcess(Process):
    def run(self) -> None:
        self.task()

    def task(self):
        # print(os.getpid(),os.getppid())
        return DesenData.main(self._kwargs)